import React, { Component } from 'react'
import axios from 'axios'

export default class App extends Component {

    state = {
        url: `https://api.github.com/search/users?q=as`
    }

    componentDidMount() {
        this.getDataByFetch()
    }

    getDataByAxios = () => {
        axios.get(this.state.url).then(
            res => {
                console.log(res.data.items.length)
            },
            err => {
                console.log('axios', err)
            })
    }

    getDataByFetch = async () => {
        /* fetch(this.state.url).then(
            res => {
                console.log('连接服务器成功')
                return res.json() // 返回一个promise实例
            }
        ).then(
            res => {
                console.log('获取数据成功', res.items.length)
            }
        ).catch(
            err => {
                console.log(err)
            }
        ) */

        // 优化
        try {
            const response = await fetch(this.state.url)
            const result = await response.json()
            console.log(result.items.length)
        } catch (err) {
            console.log('请求出错', err)
        }
    }

    render() {
        return (
            <div className="App">
                <button onClick={this.getDataByAxios}>Axios</button><br />
                <button onClick={this.getDataByFetch}>Fetch</button>
            </div>
        )
    }
}